﻿using DBServer.Selenium.Extenium.Exception;
using DBServer.Selenium.Extenium.Path;
using Selenium;

namespace DBServer.Selenium.Extenium.Fixtures
{
    public class TabPanelFixture : ExtComponentFixture
    {
        public TabPanelFixture(ISelenium driver, string name) : base(driver, new ExtComponentPath(name))
        {
        }

        public TabFixture Tab(int index)
        {
            return new TabFixture(Driver, Path, index);
        }

        public TabFixture Tab(string title)
        {
            return new TabFixture(Driver, Path, TabIndex(title));
        }



        private int TabIndex(string title)
        {
            var ok = Wait(() => FindTabByName(title) != -1);
            if(ok)
            {
                return FindTabByName(title);
            }
            throw new ExteniumException("Tab not found: " + title);
        }

        private int FindTabByName(string title)
        {
            for (var i = 0; i < TabCount(); i++)
            {
                if (title == TabTitle(i))
                    return i;
            }
            return -1;
        }

        private string TabTitle(int index)
        {
            return SafeExec(Path + ".items.items[" + index + "].title");
        }

        private int TabCount()
        {
            var eval = SafeExec(Path + ".items.items.length");
            return int.Parse(eval);
        }


        public void RequireTabNotExists(string title)
        {
            var exists = false;

            for (var i = 0; i < TabCount(); i++)
            {
                if (title == TabTitle(i))
                    exists = true;
            }

            if( exists )
                throw new ExteniumException("Tab not found: " + title);
        }
    }
}